#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4
from lxml import etree
import logging

from cvirt.cnode.libvirtXmlObject.baseDomain import XmlObject,GuestDevice

LOG = logging.getLogger(__name__)

"""
    @author jay.han
"""

class GuestInterfaceList(XmlObject):
    ROOT_NAME = "interface"
    def __init__(self, parse_xml=None, **kw):
        super(GuestInterfaceList, self).__init__(parse_xml=parse_xml,**kw)
        self._xpath = './devices/' + self.ROOT_NAME

        self.interfaces = []

    def _parse_xml(self, xmldoc):
        for dom in xmldoc.findall(self._xpath):
            interface = GuestInterface()
            interface._parse_xml(dom)
            self.interfaces.append(interface)


class GuestInterface(GuestDevice):
    ROOT_NAME = "interface"
    def __init__(self, parse_xml=None, **kw):
        super(GuestInterface, self).__init__(parse_xml=parse_xml,**kw)


        self.net_type = None
        self.target_dev = None
        self.model = None
        self.mac_addr = None
        self.script = None
        self.source_dev = None
        self.source_network = None
        self.source_mode = "private"
        self.vporttype = None
        self.vportparams = []
        self.filtername = None
        self.filterparams = []
        self.driver_name = None
        self.vif_inbound_peak = None
        self.vif_inbound_burst = None
        self.vif_inbound_average = None
        self.vif_outbound_peak = None
        self.vif_outbound_burst = None
        self.vif_outbound_average = None

    def _parse_xml(self, xmldoc):
        self.net_type = xmldoc.get('type')
        for c in xmldoc.getchildren():
            if c.tag == 'mac':
                self.mac_addr = c.get('address')
            elif c.tag == 'model':
                self.model = c.get('type')
            elif c.tag == 'driver':
                self.driver_name = c.get('name')
            elif c.tag == 'target':
                self.target_dev = c.get('dev')
            elif c.tag == 'source':
                if c.get('dev'):
                    self.source_dev = c.get('dev')
                elif c.get('network'):
                    self.source_network = c.get('network')
                else:
                    self.source_dev = c.get('bridge')
            elif c.tag == 'filterref':
                self.filtername = c.get('filter')
                for params in c.getchildren():
                    if params.tag == 'parameter':
                        self.filterparams.append(dict(name=params.get('key'),value=params.get('value')))

    def _get_xml_config(self, root):
        dev = root

        dev.set("type", self.net_type)
        dev.append(etree.Element("mac", address=self.mac_addr))
        if self.model:
            dev.append(etree.Element("model", type=self.model))

        if self.driver_name:
            dev.append(etree.Element("driver", name=self.driver_name))

        if self.net_type == "ethernet":
            if self.script is not None:
                dev.append(etree.Element("script", path=self.script))
        elif self.net_type == "direct":
            dev.append(etree.Element("source", dev=self.source_dev,
                                     mode=self.source_mode))
        elif self.net_type == 'network' :
            dev.append(etree.Element("source",network=self.source_network))
        # else:
        #     dev.append(etree.Element("source", bridge=self.source_dev))

        if self.target_dev is not None:
            dev.append(etree.Element("target", dev=self.target_dev))

        if self.vporttype is not None:
            vport = etree.Element("virtualport", type=self.vporttype)
            for p in self.vportparams:
                param = etree.Element("parameters")
                param.set(p['key'], p['value'])
                vport.append(param)
            dev.append(vport)

        if self.filtername is not None:
            filter = etree.Element("filterref", filter=self.filtername)
            for p in self.filterparams:
                filter.append(etree.Element("parameter",
                                            name=p['key'],
                                            value=p['value']))
            dev.append(filter)

        if self.vif_inbound_average or self.vif_outbound_average:
            bandwidth = etree.Element("bandwidth")
            if self.vif_inbound_average is not None:
                vif_inbound = etree.Element("inbound",
                                            average=str(self.vif_inbound_average))
                if self.vif_inbound_peak is not None:
                    vif_inbound.set("peak", str(self.vif_inbound_peak))
                if self.vif_inbound_burst is not None:
                    vif_inbound.set("burst", str(self.vif_inbound_burst))
                bandwidth.append(vif_inbound)

            if self.vif_outbound_average is not None:
                vif_outbound = etree.Element("outbound",
                                             average=str(self.vif_outbound_average))
                if self.vif_outbound_peak is not None:
                    vif_outbound.set("peak", str(self.vif_outbound_peak))
                if self.vif_outbound_burst is not None:
                    vif_outbound.set("burst", str(self.vif_outbound_burst))
                bandwidth.append(vif_outbound)
            dev.append(bandwidth)

        return dev

    def add_filter_param(self, key, value):
        self.filterparams.append({'key': key, 'value': value})

    def add_vport_param(self, key, value):
        self.vportparams.append({'key': key, 'value': value})
